package com.thermofisher.dsc.amanda.common.tracking.aspect;

import com.thermofisher.dsc.amanda.auth.mapper.UserMapper;
import com.thermofisher.dsc.amanda.auth.service.UserService;
import com.thermofisher.dsc.amanda.common.tracking.TrackingAction;
import com.thermofisher.dsc.amanda.common.util.SessionUtil;
import com.thermofisher.dsc.amanda.model.constant.ActionEnum;
import com.thermofisher.dsc.amanda.model.dto.tracking.TrackingDto;
import com.thermofisher.dsc.amanda.model.po.auth.User;
import com.thermofisher.dsc.amanda.tracking.service.TrackingService;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by wenjie.yang on 3/29/2019.
 */
@Aspect
@Component
@Slf4j
public class TrackingAspect {

  @Autowired
  private TrackingService trackingService;

  public static final String  FIRST_PAGE = "1";


  @Pointcut("@annotation(com.thermofisher.dsc.amanda.common.tracking.TrackingAction)")
  public void aspect() {

  }

  @Before("aspect()&&@annotation(anno)")
  public void doBefore(JoinPoint joinPoint,TrackingAction anno) throws Throwable {
    if(anno.action() == null){
      return ;
    }
    boolean isFirstPage = true;

    TrackingDto trackingDto = anno.action().getTracking();
    if (!anno.action().equals(ActionEnum.CLICK_LOGIN)){
      trackingDto.setUserId(SessionUtil.getUserId());
      if (joinPoint.getArgs()[0] instanceof HashMap){
        Map<String,Object> params = (HashMap<String,Object>) joinPoint.getArgs()[0];
        Object quantity = params.get("quantity");
        Object page = params.get("page");
        if (page!=null && !page.toString().equals(FIRST_PAGE)){
          isFirstPage = false;
        }
        if (quantity != null){
          Integer integer = Integer.valueOf(quantity.toString());
          trackingDto.setQuantities(integer);
        }
        Object selected = ((HashMap) joinPoint.getArgs()[0]).get("selected");
        if (selected != null && selected.toString().equals("1")){
          trackingDto = anno.action().getDifference().getTracking();
          trackingDto.setUserId(SessionUtil.getUserId());
        }
        trackingDto.setInfoCollection(this.getKeyValue(params));
      }
    }
    if (isFirstPage){
      trackingService.create(trackingDto);
    }
  }


  private String getKeyValue(Map<String,Object> params){
    StringBuffer sb = new StringBuffer("");
    for (String key:params.keySet()){
      if (!key.equals("selected")){
        sb.append(key+":"+params.get(key).toString()+";");
      }
    }
    return sb.toString();
  }
}
